<?php
/**
 * Регистрация пользователя с ajax проверкой
 *
 * @author tonatos
 */
class c_register_controller extends c_base_controller {

    protected $module="register";

    /**
     * Контроллер формы
     * @var c_form_controller
     */
    protected $form;

    public function index($params) {
        global $modx;

        $form = new c_form_controller("register_form");
        $form->add_antispam();
        $form->add_username("username", $this->template->lang['username'], "", true)
                ->set_min(3);
        $form->add_varchar("fullname", $this->template->lang['fullname'], "", true);
        $form->add_email("email", $this->template->lang['email'], "", true);
        $form->add_checkbot();
        $form->set_field_ok(true);

        //Проверка полей через ajax
        if ($params[2]=="ajax_check"){
            $fieldname = $params[3];
            $value = $params[4];

            $field = $form->get_field($fieldname);
            $field->value = $value;
            if ($field->check()){
                echo "set_field_ok('$fieldname');";
            }else{
                echo "set_field_error('$fieldname','$field->error');";
            }
            die();
        }

        //Регистрируем функции для ajax проверки
        $form->reg_ajax_check("register/index");


        if ($form->data_submitted()){
            if ($form->is_validate()){

                $data = $form->get_data();
                $this->register_with_activate($data);
                
            }
        }
        $this->form = $form;
        $this->callback=$modx->config["site_url"]."login/loginza.html";
        $this->show("index");
        
    }

    protected function register_with_activate($data){
        global $modx;

        $code = md5($this->generate_password());

        $model = new c_web_users_model($data);
        $model->cachepwd  = $code;
        $model->password  = md5(time().rand(0, 999999));
        $model->blocked   = 1;
        $model->createdon = time();
        $model->activated = 0;
        $model->save();

        //Ссылка для активации
        $activate = $modx->config['site_url']."register/activate/$model->id/$code";
        $this->send_register_mail($model->email, $model->username, $model->fullname, $activate);

        //Переходим на страницу подтверждения
        $modx->sendRedirect("/register/mail_send.html");
        die();

    }

    protected function send_register_mail($email,$username,$fullname,$activate){
        $this->template->fullname = $fullname;
        $this->template->username = $username;
        $this->template->activate = $activate;
        
        //Отправляем письмо пользователю
        $this->send_mail_from_template($email, $this->template->lang['subject_register'], "mail_register");

    }

    protected function send_fogot_mail($email,$username,$fullname,$activate){
        $this->template->fullname = $fullname;
        $this->template->username = $username;
        $this->template->activate = $activate;

        //Отправляем письмо пользователю
        $this->send_mail_from_template($email, $this->template->lang['subject_fogot'], "mail_fogot");

    }

    public function activate($params){
        global $modx;

        $user_id  = (int)$params[2];
        $activate = trim($modx->db->escape($params[3]));
        $error = "Неверный код активации";

        if ((!empty($user_id))||(!empty($activate))) {
            $user = new c_web_users_model($user_id);

            if ($user->activated!=0){
                
                if (empty($user->cachepwd)){
                    $modx->sendRedirect("/register/already_active.html");;
                }else{
                    $modx->sendRedirect("/register/set_password/$user->id/$activate");;
                }
                die();
            }

            if ($user->cachepwd==$activate){
                //Активируем
                $user->activated = time();
                $user->blocked = 0;
                $user->save();

                $modx->sendRedirect("/register/set_password/$user->id/$activate");;
                die();

            }
            
        }
        echo $error;
    }

    public function active_success(){
        $this->template->show("active_success");

        $login = new c_login_controller();
        $login->index();
    }

    public function restore_success(){
        $this->template->show("restore_success");

        $login = new c_login_controller();
        $login->index();

    }

    public function fogot_active(){
        global $modx;

        $this->form_fogot = new c_form_controller();

        $this->form_fogot->add_antispam();
        $this->form_fogot->add_email("email_fogot", $this->template->lang['email'], "", true)
                ->check_web_user(false);

        if ($this->form_fogot->data_submitted()){
            if ($this->form_fogot->is_validate()){

                $data = $this->form_fogot->get_data();
                //Ищем в базе данных
                $user = new c_web_users_model();
                if($user->find_by_email($data['email_fogot'])){
                    $user->load();
                    if ($user->activated!=0){
                        $modx->sendRedirect("/register/already_active.html");;
                        die();
                    }

                    //Ссылка для активации
                    $activate = $modx->config['site_url']."register/activate/$user->id/$user->cachepwd";
                    $this->send_register_mail($user->email, $user->username, $user->fullname, $activate);

                    //Переходим на страницу подтверждения
                    $modx->sendRedirect("/register/mail_send.html");
                    die();
                    
                }else{
                    $this->form_fogot->get_field('email')->set_error("Данный email не найден в базе данных");
                }
            }
        }

        $this->template->show("fogot_active");

        $this->form_fogot->show_form();

    }

    public function already_active(){
        $this->template->show("already_active");
    }

    public function mail_send(){
        $this->template->show("mail_send");
    }

    public function mail_send_fogot(){
        $this->template->show("mail_send_fogot");
    }

    public function __construct() {
        global $modx;
        parent::__construct();

    }

    public function fogot($params){
        global $modx;

        echo '<h1 class="pagetitle">Восстановление пароля</h1>';

        $form = new c_form_controller();
        $form->add_email("email_fogot", "Введите Ваш электронный адрес указанный при регистрации","",1)
                ->check_web_user(false);
        $form->add_antispam();



        if ($form->data_submitted()){
            if ($form->is_validate()){

                $data = $form->get_data();

                $model = new c_web_users_model();

                if (!$model->find_by_email($data['email_fogot'])){
                    $form->get_field("email_fogot")->set_error("Данный email не найден в базе данных");
                }else{
                    $model->load();

                    //Аккаунт еще не активирован
                    if (empty($model->activated)){
                        $modx->sendRedirect("/register/not_active.html");
                    }

                    if (empty($model->cachepwd)){
                        $model->cachepwd=md5($this->generate_password());
                    }

                    $model->save();

                    //Ссылка для восстановления
                    $activate = $modx->config['site_url']."register/set_password/$model->id/$model->cachepwd/fogot";
                    $this->send_fogot_mail($model->email, $model->username, $model->fullname, $activate);

                    //Переходим на страницу подтверждения
                    $modx->sendRedirect("/register/mail_send_fogot.html");
                    
                }

            }
        }else{
            if (!empty($params[2])){
                $form->get_field("email_fogot")->value = $params[2];
            }
        }

        $form->show_form();

        
    }


    public function set_password($params){
        global $modx;

        echo '<h1 class="pagetitle">Установка пароля</h1>';

        
        $user_id  = (int)$params[2];
        $activate = trim($modx->db->escape($params[3]));
        $error = "Неверный код";

        if ((!empty($user_id))||(!empty($activate))) {

            try{
                $user = new c_web_users_model($user_id);
            }  catch (Exception $e){
                echo $error;
                return;
            }


            if ($user->cachepwd!=$activate){
                echo $error;
                return;
            }



            $form = new c_form_controller();

            $form->add_varchar("password","Введите пароль","Внимание, символы отображатся!",1)
                    ->set_min(6);

            if ($form->data_submitted()){
                if ($form->is_validate()){

                    $data = $form->get_data();

                    $user->password = md5($data['password']);
                    $user->cachepwd = "";

                    $user->save();

                    if ($params[4]=="fogot"){
                        $modx->sendRedirect("/register/restore_success");
                    }else{
                        $login = new c_login_controller();
                        $modx->sendRedirect("/register/active_success");
                    }
                    
                }
            }
            
            $form->show_form();



        }else{
                echo $error;
        }
    }



}
?>
